# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import datetime
def pause():
    try:
        pause()
    except (EOFError, RuntimeError):
        pass  # 忽略无 stdin 的情况
        
def run_git_command(folder_path, command, *args):
    """
    在指定文件夹中运行 Git 命令，并输出原始错误信息。
    """
    try:
        os.chdir(folder_path)
        result = subprocess.run(["git", command, *args], check=True, text=True, capture_output=True, encoding='utf-8')
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"❌ Git 命令失败: {' '.join(['git', command, *args])}")
        print(f"📄 原始错误输出:\n{e.stderr.strip()}")
        pause()
        return None
    except Exception as e:
        print(f"⚠️ 意外错误类型: {type(e).__name__}")
        print(f"📄 原始异常信息: {e}")
        pause()
        return None

def git_init(folder_path):
    """
    初始化一个新的 Git 仓库。
    
    :param folder_path: 目标文件夹路径
    """
    print(f"正在 {folder_path} 中初始化 Git 仓库...")
    output = run_git_command(folder_path, "init")
    if output is not None:
        print("Git 仓库初始化成功。")

def git_clone(folder_path):
    """
    克隆一个远程 Git 仓库。
    
    :param folder_path: 目标文件夹路径
    """
    print(f"正在将远程仓库克隆到 {folder_path}...")
    repo_url = input("请输入远程仓库的 URL: ").strip()
    if not repo_url:
        print("远程仓库 URL 不能为空。")
        pause()
        return
    output = run_git_command(folder_path, "clone", repo_url)
    if output is not None:
        print("远程仓库克隆成功。")


def git_add(folder_path):
    """
    将所有更改添加到暂存区，并忽略大于等于10MB的文件。
    
    :param folder_path: 目标文件夹路径
    """
    print(f"正在 {folder_path} 中扫描大于等于10MB的文件并更新 .gitignore...")

    gitignore_path = os.path.join(folder_path, '.gitignore')
    large_files = []

    # 遍历目录，找出大于等于10MB的文件
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                if os.path.isfile(file_path) and os.path.getsize(file_path) >= 10 * 1024 * 1024:
                    # 计算相对路径并转为Unix风格
                    rel_path = os.path.relpath(file_path, folder_path).replace("\\", "/")
                    large_files.append(rel_path)
            except Exception as e:
                print(f"无法读取文件大小: {file_path}，错误: {e}")
                pause()

    # 读取已有的 .gitignore 内容（如果存在）
    existing_ignores = set()
    if os.path.isfile(gitignore_path):
        with open(gitignore_path, 'r', encoding='utf-8') as f:
            existing_ignores = set(line.strip() for line in f if line.strip())

    # 添加新的大文件路径到 .gitignore
    new_entries = set(large_files) - existing_ignores
    if new_entries:
        with open(gitignore_path, 'a', encoding='utf-8') as f:
            for entry in sorted(new_entries):
                f.write(entry + '\n')
        print(f"已将 {len(new_entries)} 个大于等于10MB的文件添加到 .gitignore。")
        pause()
    else:
        print("没有新的大文件需要添加到 .gitignore。")
        pause()

    # 执行 git add
    print(f"正在 {folder_path} 中暂存所有更改...")
    output = run_git_command(folder_path, "add", "-A")
    if output is not None:
        print("更改暂存成功。")


def git_commit(folder_path):
    """
    提交暂存的更改。
    :param folder_path: 目标文件夹路径
    """
    try:
        now = datetime.datetime.now()
        commit_message = now.strftime("%Y年%m月%d日_%H:%M")
        print(f"正在 {folder_path} 中提交更改，提交信息为: '{commit_message}'")
        output = run_git_command(folder_path, "commit", "-a", "-m", commit_message)
        if output is not None:
            print("更改提交成功。")
            pause()
        else:
            print("提交失败。")
            pause()
    except Exception as e:
        print(f"发生错误: {e}")
        pause()
        


def git_push(folder_path):
    """
    将更改推送到远程仓库的 main 分支。
    :param folder_path: 目标文件夹路径
    """
    print(f"正在将 {folder_path} 中的更改推送到远程仓库的 main 分支...")
    output = run_git_command(folder_path, "push", "origin", "main")
    if output is not None:
        print("更改推送成功。")

def git_pull(folder_path):
    """
    从远程仓库拉取最新的更改。
    
    :param folder_path: 目标文件夹路径
    """
    print(f"正在从远程仓库拉取最新的更改到 {folder_path}...")
    output = run_git_command(folder_path, "pull", "origin", "main")
    if output is not None:
        print("拉取成功。")
    else:
        print("拉取失败，请检查网络连接或远程仓库地址。")
        pause()

def main():
    """
    主函数，解析命令行参数并调用相应的 Git 操作。
    """
    if len(sys.argv) < 3:
        print("用法: script.py <命令> <文件夹路径>")
        return

    command = sys.argv[1].lower()  # 获取命令并转换为小写
    folder_path = sys.argv[2]  # 获取目标文件夹路径

    if not os.path.isdir(folder_path):
        print("无效的文件夹路径")
        pause()
        return

    # 根据命令调用相应的函数
    commands = {
        "init": git_init,
        "clone": git_clone,
        "add": git_add,
        "commit": git_commit,
        "push": git_push,
        "pull": git_pull  # 新增 pull 命令
    }

    if command in commands:
        commands[command](folder_path)
    else:
        print("未知命令")
        pause()

if __name__ == "__main__":
    main()
